package com.offcn.test;

import java.util.concurrent.CountDownLatch;

/**
 * 关键字防止重排序
 */
public class VolatailTest2 {
    static int a,b,x,y;
    public static void main(String[] args) throws Exception{
        for (int i=1;;i++){
            a = b = x = y =0;
            CountDownLatch cd = new CountDownLatch(2);
            new Thread(()->{
                y=1;
                a=x;
                cd.countDown();
            }).start();
            new Thread(()->{
                x=1;
                b=y;
                cd.countDown();
            }).start();
            cd.await();//阻塞当前线程,直到计数器为0
            System.out.println("第"+i+"次,a = "+a+";b = "+b);
            if (a == 0 && b==0){
                break;
            }
        }
    }
}
